import os
import xml.etree.ElementTree as ET
import matplotlib.pyplot as plt
from matplotlib.patches import PathPatch
from matplotlib.path import Path as MplPath
import re

# 解析颜色的函数
def parse_rgb(style):
    match = re.search(r'fill:rgb\(([\d.%]+),([\d.%]+),([\d.%]+)\)', style)
    if match:
        r, g, b = match.groups()
        if '%' in r:
            return tuple(float(c.strip('%')) / 100 for c in (r, g, b))
        else:
            return tuple(float(c) / 255 for c in (r, g, b))
    match_hex = re.search(r'fill:\s*#([0-9a-fA-F]{6})', style)
    if match_hex:
        hex_color = match_hex.group(1)
        r = int(hex_color[0:2], 16) / 255
        g = int(hex_color[2:4], 16) / 255
        b = int(hex_color[4:6], 16) / 255
        return (r, g, b)
    return (0, 0, 0)  # 默认黑色

# 处理单个 SVG 文件的函数
def process_svg(svg_file, output_folder):
    with open(svg_file, 'r', encoding='utf-8') as f:
        content = f.read()

    # 获取 SVG 的宽高
    width_match = re.search(r'width="([\d.]+)(?:pt|px)?"', content)
    height_match = re.search(r'height="([\d.]+)(?:pt|px)?"', content)

    if width_match and height_match:
        svg_width = float(width_match.group(1))
        svg_height = float(height_match.group(1))
    # 设置画布
    fig, ax = plt.subplots(figsize=(svg_width, svg_height))
    ax.set_aspect('equal')
    ax.set_facecolor('white')

    # 加载并筛选 path 元素
    tree = ET.parse(svg_file)
    root = tree.getroot()

    for elem in root.iter('{http://www.w3.org/2000/svg}path'):
        d = elem.attrib.get('d', '')
        style = elem.attrib.get('style', "")
        fill_color = parse_rgb(style)

        # 排除包含 L/Z 的路径（通常是矩形）
        if 'L' in d or 'Z' in d or 'z' in d:
            continue

        # 解析路径数据
        path_data = re.findall(r'[A-Za-z]|-?\d*\.?\d+', d)
        if path_data and path_data[0] == 'M':
            verts = []
            codes = []
            i = 0
            while i < len(path_data):
                cmd = path_data[i]
                i += 1
                if cmd == 'M':
                    x = float(path_data[i])
                    y = float(path_data[i + 1])
                    verts.append((x, y))
                    codes.append(MplPath.MOVETO)
                    i += 2
                elif cmd == 'C':
                    for _ in range(3):
                        x = float(path_data[i])
                        y = float(path_data[i + 1])
                        verts.append((x, y))
                        codes.append(MplPath.CURVE4)
                        i += 2
                else:
                    break

            if verts:
                mpl_path = MplPath(verts, codes)
                patch = PathPatch(mpl_path, facecolor=fill_color, edgecolor='none')
                ax.add_patch(patch)

    # 设置画布
    ax.autoscale_view()
    plt.gca().invert_yaxis()
    plt.axis('off')

    # 保存结果图像
    output_file = os.path.join(output_folder, os.path.basename(svg_file).replace('.svg', '.png'))
    plt.savefig(output_file, dpi=10, bbox_inches=None, pad_inches=0)
    plt.close()
    print(f"✅ 图像已保存为 {output_file}，仅包含圆形路径")

# 批量处理文件夹中的 SVG 图片
def batch_process_svg(input_folder, output_folder):
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # 遍历文件夹中的所有 SVG 文件
    for filename in os.listdir(input_folder):
        if filename.lower().endswith('.svg'):
            svg_file = os.path.join(input_folder, filename)
            process_svg(svg_file, output_folder)

# 示例：指定输入和输出文件夹
input_folder = r"C:\Users\cenkai\Desktop\PCB_Detection\svg"
output_folder = r"C:\Users\cenkai\Desktop\PCB_Detection\cir_output"

batch_process_svg(input_folder, output_folder)
